#!/usr/bin/env bash

START=$(date +%s)

SERVICE=lake

GROUP_ID="com.lakeworks"
ARTIFACT_ID="lakeworks-admin"
GROUP_PATH=$(echo "${GROUP_ID}" | sed 's/\./\//g')

REPO_BUCKET="repo.dajingxiapp.com"
REPO_URL="s3://${REPO_BUCKET}/snapshots/${GROUP_PATH}"

TARGET_DIR="${HOME}"
LINK_NAME="${ARTIFACT_ID}"

VERSION=$1

echo "Checking latest version"
VERSION=$(aws s3 cp ${REPO_URL}/${ARTIFACT_ID}/maven-metadata.xml - | xmllint --xpath '/metadata/versioning/versions/version[last()]/text()' -)
echo "Releasing ${GROUP_ID}:${ARTIFACT_ID} ${VERSION}"

SUFFIX=$(aws s3 cp ${REPO_URL}/${ARTIFACT_ID}/${VERSION}/maven-metadata.xml - | xmllint --xpath '/metadata/versioning/snapshotVersions/snapshotVersion[./extension[text() = "tar.gz"]]/value/text()' -)

FILENAME="${ARTIFACT_ID}-${SUFFIX}"

DIR="${TARGET_DIR}/${FILENAME}"
mkdir "${DIR}" >> /dev/null
if [ $? -gt 0 ]; then
	echo "Failed to mkdir ${DIR}"
	exit 1
fi

TGZ_URL="${REPO_URL}/${ARTIFACT_ID}/${VERSION}/${FILENAME}.tar.gz"
echo "Downloading ${TGZ_URL}"
aws s3 cp ${TGZ_URL} - | tar zx -C "${DIR}"
echo "Files extracted to ${DIR}"

systemctl --user status ${SERVICE} --no-pager -l
systemctl --user stop ${SERVICE}
ln -snvf "${FILENAME}" "${TARGET_DIR}/${LINK_NAME}"
systemctl --user start ${SERVICE}
systemctl --user status ${SERVICE} --no-pager -l

echo "All Done in $(($(date +%s) - ${START})) seconds"
